package cn.cjlmonster.demo02.ui;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.GradientDrawable;
import android.view.View;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.cjlmonster.demo02.ChartDialog;
import cn.cjlmonster.demo02.R;
import cn.cjlmonster.demo02.base.BaseAppCompatActivity;
import cn.cjlmonster.demo02.data.SnapshotData;
import cn.cjlmonster.demo02.entity.Snapshot;
import cn.cjlmonster.demo02.utils.DpUtils;
import cn.cjlmonster.demo02.widget.MyMarkerView;
import cn.cjlmonster.demo02.widget.RadialCircleMarketView;

/**
 * This project is Demo02
 * Created by cjl on 2021/11/19 9:54 下午.
 */
public class ChartActivity extends BaseAppCompatActivity {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chart;
    }

    @Override
    protected boolean canBack() {
        return true;
    }

    public void showDialog(View view) {
        ChartDialog.show(view.getContext());
    }

    public void updateDataSet(View v) {
        initData();
    }

    private LineChart lineChart;
    private BarChart barChart;

    @Override
    protected void initView() {
        lineChart = findViewById(R.id.lineChart);
        lineChart.setScaleEnabled(false);
        lineChart.setPinchZoom(false);

        barChart = findViewById(R.id.barChart);
        barChart.setScaleEnabled(false);
        barChart.setPinchZoom(false);

    }

    @Override
    protected void initData() {
        List<Snapshot> mSnapshots = SnapshotData.createSnapshots(SnapshotData.Unit.day);

        initLineChart(mSnapshots);

        initBarChart(mSnapshots);
    }

    private int currentSelectedIndex;

    private void initLineChart(List<Snapshot> mSnapshots) {

//        lineChart.reset();
        float max = 0;
        List<Entry> mEntries = new ArrayList<>();
        for (int i = 0; i < mSnapshots.size(); i++) {
            float value = mSnapshots.get(i).getValue();
            if (value > max) {
                max = value;
            }
            mEntries.add(new Entry(i, value));
        }
        LineDataSet dataSet = new LineDataSet(mEntries, "用电量");
        dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        dataSet.setCubicIntensity(0.2f);
        dataSet.setDrawCircleHole(false);
        dataSet.setDrawCircles(false);
        dataSet.setDrawFilled(false);
        dataSet.setColor(Color.parseColor("#31FDFF"));
        dataSet.setLineWidth(DpUtils.dpToPx(this, 1));
        GradientDrawable drawable = new GradientDrawable(
                GradientDrawable.Orientation.TOP_BOTTOM,
                new int[]{
                        Color.parseColor("#FF891289"),
                        Color.parseColor("#30000000")
                }
        );
        dataSet.setFillDrawable(drawable);
        dataSet.setDrawHighlightIndicators(false);
        dataSet.setHighLightColor(Color.RED);
        dataSet.setDrawHorizontalHighlightIndicator(false);
        dataSet.setDrawValueCenter(true);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setDrawAxisLine(true);
//        xAxis.setDrawLimitLinesBehindData(true);
        xAxis.setDrawLabels(true);
        xAxis.setDrawGridLines(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//        xAxis.setAxisMinimum(0f);//设置轴的最小值。这样设置将不会根据提供的数据自动计算。
        xAxis.setGranularityEnabled(true);    //粒度
        xAxis.setGranularity(1f);    //缩放的时候有用，比如放大的时候，我不想把横轴的月份再细分
        xAxis.setValueFormatter(new UnitValueFormatter(mSnapshots));

        xAxis.setAvoidFirstLastClipping(true);

        xAxis.enableAxisLineDashedLine(10, 10, 0);
        xAxis.enableGridDashedLine(10, 10, 0);
        xAxis.setCenterAxisLabels(true);
        xAxis.setSpaceMax(1);

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setEnabled(true);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setDrawLabels(false);
//        leftAxis.setAxisMinimum(0);
//        leftAxis.setAxisMaximum(max);
        leftAxis.setLabelCount(7, true);
        leftAxis.setDrawGridLines(false);
        leftAxis.enableAxisLineDashedLine(10, 10, 0);

        YAxis rightAxis = lineChart.getAxisRight();
        rightAxis.setEnabled(true);
        rightAxis.setDrawAxisLine(true);
        rightAxis.setDrawGridLines(true);
//        rightAxis.setAxisMinimum(0);
//        rightAxis.setAxisMaximum(max);
        rightAxis.setLabelCount(7, true);
        rightAxis.enableGridDashedLine(10, 10, 0);
        rightAxis.enableAxisLineDashedLine(10, 10, 0);

        LineData lineData = new LineData(dataSet);
        lineData.setDrawValues(false);

        lineChart.setData(lineData);

//        MyMarkerView markerView = new MyMarkerView(this) {
//            @Override
//            protected void onItemSelected(int xPos, TextView msg) {
//                float i = mSnapshots.get(xPos).getValue();
//                msg.setText(String.format("i = %s", i));
//            }
//        };
        RadialCircleMarketView markerView = new RadialCircleMarketView(this);
        markerView.setChartView(lineChart);
        lineChart.setMarker(markerView);

        lineChart.setDescription(null);

        lineChart.getLegend().setEnabled(false);

        lineChart.fitScreen();

        //设置一页最大显示个数为6，超出部分就滑动
        float ratio = (float) mEntries.size() / (float) 6;
        //显示的时候是按照多大的比率缩放显示,1f表示不放大缩小
        lineChart.zoom(ratio, 1f, 0, 0);
        //设置从X轴出来的动画时间
        lineChart.animateXY(1500, 1500, Easing.EaseOutSine, Easing.EaseOutSine);
        //设置XY轴动画
//        lineChart.animateXY(1500,1500, Easing.EaseInSine, Easing.EaseInSine);

//        lineChart.invalidate();
        lineChart.highlightValue(0, 0);
    }

    private void initBarChart(List<Snapshot> mSnapshots) {

        barChart.reset();

        List<BarEntry> mEntries = new ArrayList<>();
        for (int i = 0; i < mSnapshots.size(); i++) {
            mEntries.add(new BarEntry(i, mSnapshots.get(i).getValue()));
        }

        BarDataSet dataSet = new BarDataSet(mEntries, "总用电量");
        dataSet.setDrawValues(false);
        dataSet.setColor(Color.LTGRAY);

        dataSet.setGradientColor(Color.LTGRAY, Color.RED);

        BarData barData = new BarData(dataSet);


        barData.setBarWidth(.2f);
        barChart.getXAxis().setDrawAxisLine(true);
        barChart.getXAxis().setDrawGridLines(false);
        barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
//        barChart.getXAxis().setAxisMinimum(0f);
        barChart.getXAxis().setGranularity(1f);
        barChart.getXAxis().setValueFormatter(new UnitValueFormatter(mSnapshots));
//        barChart.getXAxis().setYOffset(-3f);
        barChart.getAxisLeft().setDrawGridLines(false);
        barChart.getAxisLeft().setAxisMinimum(0);
        barChart.getAxisRight().setEnabled(false);

        barData.setDrawRoundBar(true);


        barChart.setData(barData);

        barChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                currentSelectedIndex = (int) e.getX();
            }

            @Override
            public void onNothingSelected() {
                barChart.highlightValue(currentSelectedIndex, 0);
            }
        });

        barChart.setDescription(null);
        barChart.setDrawBarShadow(false);

        Legend legend = barChart.getLegend();
        legend.setForm(Legend.LegendForm.CIRCLE);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);

        barChart.fitScreen();

////        设置一页最大显示个数为6，超出部分就滑动
        float ratio = (float) mEntries.size() / (float) barChart.getXAxis().getLabelCount();
////        //显示的时候是按照多大的比率缩放显示,1f表示不放大缩小
        barChart.zoom(ratio, 1f, 0, 0);

        barChart.setExtraBottomOffset(38);

        barChart.moveViewToX(mEntries.size() - 1);
        barChart.highlightValue(mEntries.size() - 1, 0);

        MyMarkerView myMarkerView = new MyMarkerView(this) {
            @Override
            protected void onItemSelected(int xPos, TextView msg) {
                float i = mSnapshots.get(xPos).getValue();
                msg.setText(String.format("i = %s", i));
            }
        };
        myMarkerView.setChartView(barChart);
        barChart.setMarker(myMarkerView);

        barChart.animateXY(1500, 1500);
    }

    private static class UnitValueFormatter extends ValueFormatter {


        private final List<Snapshot> mSnapshots;

        public UnitValueFormatter(List<Snapshot> mSnapshots) {
            this.mSnapshots = mSnapshots;
        }

        private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

        @Override
        public String getFormattedValue(float value) {
            String valueString = value + "";
            try {
                Date date = sdf.parse(mSnapshots.get((int) value).getDate());
                Calendar c = Calendar.getInstance();
                c.setTime(date);

                int d = c.get(Calendar.DAY_OF_MONTH);
                valueString = String.format("%s日", d);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return valueString;
        }
    }
}
